<!--
- File:    添加花园.
-->
<template>
  <div class="Web_Box">
    <div class="add_time2 f-cb bg_fff">
      <!--<i class="iconfont icon-bianji" style="vertical-align: bottom"></i>-->
      <span style="display: inline-block; font-size: 14px;color: #221814">植物名：</span>
      <input type="text" class="g_ipts" style="font-size: 14px; display: inline-block; width: 80%;" placeholder="输入植物名称" v-model="plantName">
    </div>
    <div class="Plantpictures">
      <div class="Plantinp" v-show="plantImg ==''">
        <div id="select-pic">
          <input type="file" id="fileInput1" accept="image/jpeg,image/jpg,image/png,image/gif" style="display: none" @change="fileSelected">
        </div>
        <i class="iconfont icon-uayuanwen" @click="getImg" style="pointer-events: auto"></i>
      </div>
      <div class="Plantinp" v-show="plantImg !=''">
        <div class="Plantimg ">
          <div class="blacks"></div>
          <img :src="$config.imgsite + $config.uploadImgSrc + plantImg + '_w640h320'">
          <div class="operation"><span @click="getImg">重新上传</span><span @click="delImg">删除</span></div>
        </div>
      </div>
    </div>
    <div class="Fillinformation" style="padding: 0;border-bottom: 1px #eee solid" v-show="gardenType == $dictionary.gardenType.share">
      <div class="Fill_input f-cb" style="color: #221814; background: #fff;margin-bottom: 0">
        <label>共享开始时间<span type="text" @click="openBeginDatePicker" style="float: right">{{beginDate == null ? '点击选择时间' : beginDate}}</span></label>
      </div>
    </div>
    <div class="Fillinformation" style="padding: 0; margin-top: 0" v-show="gardenType == $dictionary.gardenType.share">
      <div class="Fill_input f-cb" style="color: #221814; background: #fff">
        <label>共享结束时间<span type="text" @click="openEndDatePicker" style="float: right">{{endDate == null ? '点击选择时间' : endDate}}</span></label>
      </div>
    </div>
    <div class="select_tit">
      <p>选择健康状态</p>
      <div class="graden_cont5">
        <ul class="f-cb">
          <li v-for="health in plantAttr.health" @click="clickItem('health', health)">
            <div class="graden_bg5"><img :src="$config.imgsite + $config.uploadImgSrc + health.d_image + '_w150'">
              <i class="iconfont icon-xuanze" v-show="health.selected"></i>
            </div>
            <h3>{{health.d_name}}</h3>
          </li>
        </ul>
      </div>
    </div>
    <div class="select_tit">
      <p>成长状态</p>
      <div class="graden_cont5">
        <ul class="f-cb">
          <li @click="switchStatus($dictionary.growthStatus.seed)">
            <div class="graden_bg5"><img src="../../../assets/images/demo/grow1.png">
              <i class="iconfont icon-xuanze" v-show="selectedStatus == $dictionary.growthStatus.seed"></i>
            </div>
            <h3>种子期</h3>
          </li>
          <li @click="switchStatus($dictionary.growthStatus.sprout)">
            <div class="graden_bg5"><img src="../../../assets/images/demo/grow3.png">
              <i class="iconfont icon-xuanze" v-show="selectedStatus == $dictionary.growthStatus.sprout"></i>
            </div>
            <h3>发芽期</h3>
          </li>
          <li @click="switchStatus($dictionary.growthStatus.seedling)">
            <div class="graden_bg5"><img src="../../../assets/images/demo/grow4.png">
              <i class="iconfont icon-xuanze" v-show="selectedStatus == $dictionary.growthStatus.seedling"></i>
            </div>
            <h3>小苗期</h3>
          </li>
          <li @click="switchStatus($dictionary.growthStatus.growthed)">
            <div class="graden_bg5"><img src="../../../assets/images/demo/grow5.png">
              <i class="iconfont icon-xuanze" v-show="selectedStatus == $dictionary.growthStatus.growthed"></i>
            </div>
            <h3>成株期</h3>
          </li>
        </ul>
      </div>
    </div>
    <div class="select_tit">
      <p>选择载体</p>
      <div class="graden_cont5">
        <ul class="f-cb">
          <li v-for="basin in plantAttr.basin" @click="clickItem('basin', basin)">
            <div class="graden_bg5"><img :src="$config.imgsite + $config.uploadImgSrc + basin.d_image + '_w150'">
              <i class="iconfont icon-xuanze" v-show="basin.selected"></i>
            </div>
            <h3>{{basin.d_name}}</h3>
          </li>
        </ul>
      </div>
    </div>
    <div class="select_tit">
      <p>选择基质</p>
      <div class="graden_cont5">
        <ul class="f-cb">
          <li v-for="dirt in plantAttr.dirt" @click="clickItem('dirt', dirt)">
            <div class="graden_bg5"><img :src="$config.imgsite + $config.uploadImgSrc + dirt.d_image + '_w150'">
              <i class="iconfont icon-xuanze" v-show="dirt.selected"></i>
            </div>
            <h3>{{dirt.d_name}}</h3>
          </li>
        </ul>
      </div>
    </div>
    <div class="select_tit">
      <p>选择场景</p>
      <div class="graden_cont5">
        <ul class="f-cb">
          <li v-for="environment in plantAttr.environment" @click="clickItem('environment', environment)">
            <div class="graden_bg5"><img :src="$config.imgsite + $config.uploadImgSrc + environment.d_image + '_w150'">
              <i class="iconfont icon-xuanze" v-show="environment.selected"></i>
            </div>
            <h3>{{environment.d_name}}</h3>
          </li>
        </ul>
      </div>
    </div>
    <div class="buttonfinish" @click="updatePlantInfo"><a>提交</a></div>
    <mt-actionsheet
      :actions="actions"
      v-model="sheetVisible">
    </mt-actionsheet>
    <datetime-picker
      ref="beginDatePicker"
      type="date"
      year-format="{value} 年"
      month-format="{value} 月"
      date-format="{value} 日"
      @confirm="handleBeginDateChange">
    </datetime-picker>
    <datetime-picker
      ref="endDatePicker"
      :startDate="new Date()"
      type="date"
      year-format="{value} 年"
      month-format="{value} 月"
      date-format="{value} 日"
      @confirm="handleEndDateChange">
    </datetime-picker>
  </div>
</template>

<script>
  import vueArea from '../../../components/area'
  import {Actionsheet} from 'mint-ui'
  import * as request from '../../../request'
  import DatetimePicker from '../../../components/dateTimePicker'

  export default{
    beforeRouteEnter (to, from, next) {
      request.getPlantAttr().then(data => {
        next(vm => {
          vm.plantAttr = data
        })
      }).catch(e => {
        next()
      })
    },
    data() {
      return {
        plantId: this.$route.params.id,
        gardenType: this.$dictionary.gardenType.private,
        selectedHealthId: '', // 选中的健康状态id
        selectedStatus: '', // 选中的成长状态
        selectedBasinId: '', // 选中的载体id
        selectedDirtId: '', // 选中的基质id
        selectedEnvironmentId: '', // 选中的场景id
        plantName: '',
        plantImg: '',
        beginDate: null,
        endDate: null,
        plantAttr: {basin: [], dirt: [], environment: [], health: []},
        areaSelectShow: false,
        areaResult: {province: {code: '', name: ''}, city: {code: '', name: ''}, area: {code: '', name: ''}},
        sheetVisible: false,
        actions: [{
          name: '拍照',
          method: this.getFromCamera
        }, {
          name: '从相册选取',
          method: this.getFromAlbum
        }]
      }
    },
    components: {
      'datetimePicker': DatetimePicker,
      'vue-area': vueArea,
      'mt-actionsheet': Actionsheet
    },
    beforeRouteLeave  (to, from, next) {
      this.$indicator.close()
      next()
    },
    created() {
      // this.$native.weixinShare(window.location.href)
      this.getPlantInfo()
    },
    mounted() {
      this.$native.weixinShare(window.location.href, '遇花园', null, '')
    },
    computed: {
      addressTxt: function () {
        if (this.areaResult.province.name == '') {
          return ''
        }
        return this.areaResult.province.name + ' ' + this.areaResult.city.name + ' ' + this.areaResult.area.name
      }
    },
    methods: {
      openBeginDatePicker() {
        this.$refs.beginDatePicker.open()
      },
      openEndDatePicker() {
        this.$refs.endDatePicker.open()
      },
      handleBeginDateChange(value) {
        let date = new Date(value)
        let dateStr = this.$utils.formatDate(date, 'yyyy-MM-dd')
        this.beginDate = dateStr
      },
      handleEndDateChange(value) {
        let date = new Date(value)
        let dateStr = this.$utils.formatDate(date, 'yyyy-MM-dd')
        this.endDate = dateStr
      },
      switchStatus(value) {
        this.selectedStatus = value
      },
      getPlantInfo() {
        this.$request.getPlantInfo(this.plantId).then(data => {
          if (data.sg_id != '0') {
            this.gardenType = this.$dictionary.gardenType.share
          }
          this.plantName = data.flower_name
          this.plantImg = data.flower_image
          this.selectedStatus = data.growth_status
          this.beginDate = data.start_time && this.$utils.timestampToDate(data.start_time, 'yyyy-MM-dd')
          this.endDate = data.start_time && this.$utils.timestampToDate(data.end_time, 'yyyy-MM-dd')
          this.setSelectedPlantAttr('health', data.h_id)
          this.setSelectedPlantAttr('basin', data.ba_id)
          this.setSelectedPlantAttr('dirt', data.di_id)
          this.setSelectedPlantAttr('environment', data.en_id)
        })
      },
      setSelectedPlantAttr(type, id) {
        let list = []
        switch (type) {
          case 'basin':
            list = this.plantAttr.basin
            break
          case 'dirt':
            list = this.plantAttr.dirt
            break
          case 'environment':
            list = this.plantAttr.environment
            break
          case 'health':
            list = this.plantAttr.health
            break
        }
        for (let i = 0; i < list.length; i++) {
          if (list[i].d_id == id) {
            this.$set(list[i], 'selected', true)
            this.setSelectedId(type, list[i].d_id)
            continue
          }
          if (list[i].selected) {
            list[i].selected = false
          }
        }
      },
      getImg() {
        let deviceType = this.$utils.getDeviceType()
        if (deviceType == 'wx-iPhone' || deviceType == 'wx-Android') {
          wx.chooseImage({ // eslint-disable-line
            count: 1, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: (res) => {
              var localId = res.localIds[0]
              wx.getLocalImgData({ // eslint-disable-line
                localId: localId,
                success: (res) => {
                  var localData = res.localData
                  localData = localData.replace('jgp', 'jpeg')
                  if (localData.indexOf('data:image/jpeg;base64,') == -1) {
                    localData = 'data:image/jpeg;base64,' + localData
                  }
                  this.$indicator.open('上传图片中...')
                  this.$request.uploadImg(localData).then(data => {
                    this.plantImg = data[0]
                  }).catch(e => {
                    this.$toast('上传图片失败:' + e.msg)
                  }).finally(() => {
                    this.$indicator.close()
                  })
                }
              })
            }
          })
        } else if (deviceType == 'iPhone') {
          this.getFromAlbum() // 因为iphone不带capture属性的input 点击后本身就会弹出选择图库或拍照
        } else {
          this.sheetVisible = true
        }
      },
      getFromCamera() {
        var imgInputFile = document.getElementById('fileInput1')
        if (!imgInputFile.hasAttribute('capture')) {
          imgInputFile.setAttribute('capture', 'camera')
        }
        this.$utils.clickFileInput(imgInputFile)
      },
      getFromAlbum() {
        var imgInputFile = document.getElementById('fileInput1')
        if (imgInputFile.hasAttribute('capture')) {
          imgInputFile.removeAttribute('capture')
        }
        this.$utils.clickFileInput(imgInputFile)
      },
      delImg() {
        this.$messageBox.confirm('确定删除图片?').then(action => {
          this.plantImg = ''
        }).catch(() => {
        })
      },
      switchAreaSelectShow(boolValue) {
        this.areaSelectShow = boolValue
      },
      areaSelected(areaSelectShow, result) {
        this.areaSelectShow = areaSelectShow
        this.areaResult = result
      },
      clearInputFile() {
        var self = this
        var selectPic = document.getElementById('select-pic')
        var randomStr = Math.random().toString(36)
        selectPic.innerHTML = '<input id="fileInput1" type="file" title="" ' + randomStr + '"  accept="image/jpeg,image/jpg,image/png,image/gif"  id="fileInput1" style="visibility: hidden" >'
        document.getElementById('fileInput1').addEventListener('change', self.fileSelected)
      },
      fileSelected(e) {
        try {
          var reader = new window.FileReader()
          reader.onload = (e) => {
            if (e.total > 1024 * 1024 * 5) {
              this.$toast('图片大小不能超过5M')
              return
            }
            // 调用图片压缩方法
            // console.log("成功加载图片，开始压缩图片...")
            this.$utils.compress(e.target.result, (imgDataUrl) => {
              // todo 调用上传图片接口
              this.$request.uploadImg(imgDataUrl).then(data => {
                this.plantImg = data[0]
              }).catch(e => {
                this.$toast('上传图片失败:' + e.msg)
              })
            })
          }
          // 选取同名文件不会再次触发change事件，所以在加载后替换input控件
          reader.onloadend = (e) => {
            this.clearInputFile()
          }
          reader.readAsDataURL(e.target.files[0])
        } catch (e) {
          console.log('读取图片文件发生了错误')
          console.log(e)
        }
      },
      clickItem(type, item) { // type: 'basin' 载体， 'dirt' 基质, 'environment' 场景
        if (this.action == 'view') { // 查看百科
          this.gotoWiki(item.d_id)
        } else {
          if (item.selected) {
            item.selected = false
            this.setSelectedId(type, '')
          } else {
            this.$set(item, 'selected', true)
            this.setSelectedId(type, item.d_id)
            this.clearOthersSelected(type, item.d_id)
          }
        }
      },
      setSelectedId(type, value) {
        switch (type) {
          case 'basin':
            this.selectedBasinId = value
            break
          case 'dirt':
            this.selectedDirtId = value
            break
          case 'environment':
            this.selectedEnvironmentId = value
            break
          case 'health':
            this.selectedHealthId = value
            break
        }
      },
      clearOthersSelected(type, id) {
        let list = []
        switch (type) {
          case 'basin':
            list = this.plantAttr.basin
            break
          case 'dirt':
            list = this.plantAttr.dirt
            break
          case 'environment':
            list = this.plantAttr.environment
            break
          case 'health':
            list = this.plantAttr.health
            break
        }
        for (let i = 0; i < list.length; i++) {
          if (list[i].d_id == id) {
            continue
          }
          if (list[i].selected) {
            list[i].selected = false
          }
        }
      },
      updatePlantInfo() {
        if (this.plantName.trim() == '') {
          this.$toast('请输入植物名称')
          return
        }
        if (this.selectedHealthId == '') {
          this.$toast('请选择健康状态')
          return
        }
        if (this.selectedStatus == '') {
          this.$toast('请选择成长状态')
          return
        }
        if (this.selectedBasinId == '') {
          this.$toast('请选择载体')
          return
        }
        if (this.selectedDirtId == '') {
          this.$toast('请选择基质')
          return
        }
        if (this.selectedEnvironmentId == '') {
          this.$toast('请选择场景')
          return
        }
        let param = {
          o_id: this.plantId,
          h_id: this.selectedHealthId,
          growth_status: this.selectedStatus,
          ba_id: this.selectedBasinId,
          di_id: this.selectedDirtId,
          en_id: this.selectedEnvironmentId,
          flower_name: this.plantName,
          flower_image: this.plantImg,
          start_time: this.beginDate,
          end_time: this.endDate
        }
        this.$request.updatePlantInfo(param).then(data => {
          this.$toast('更新植物信息成功')
          this.$router.go(-1)
        }).catch(e => {
          this.$toast('更新失败:' + e.msg)
        })
      }
    }
  }
</script>

<style>

</style>